'use strict';

const BaseService = require('./base');

class CourseRecordService extends BaseService {
  constructor(ctx) {
    super(ctx, 'CourseRecord');
  }
  getPage(where, page, pageSize) {
    return this.ctx.model[this.modelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order: this.pageOrder() || [],
      include: [
        {
          model: this.ctx.model.Student,
          as: 'student',
        },
        {
          model: this.ctx.model.Parent,
          as: 'parent',
        }
      ]
    });
  }
  // 课程报名
  async signup(data) {
    const { ctx, app } = this;
    const transaction = await app.model.transaction();

    try {
      // 创建报名记录
      const record = await ctx.model.CourseRecord.create(data, { transaction });

      // 更新课程报名人数
      await ctx.model.Course.increment('signed_count', {
        by: 1,
        where: { id: data.course_id },
        transaction
      });

      await transaction.commit();
      return record;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  // 取消报名
  async cancel(id) {
    const { ctx, app } = this;
    const transaction = await app.model.transaction();

    try {
      // 更新报名状态
      const record = await ctx.model.CourseRecord.findByPk(id, { transaction });
      await record.update({ status: 0 }, { transaction });

      // 减少课程报名人数
      await ctx.model.Course.decrement('signed_count', {
        by: 1,
        where: { id: record.course_id },
        transaction
      });

      await transaction.commit();
      return record;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  // 获取报名列表
  async list(where = {}) {
    const { ctx } = this;
    return await ctx.model.CourseRecord.findAll({
      where,
      include: [{
        model: ctx.model.Course,
        as: 'course',
      }],
      order: [['create_time', 'DESC']]
    });
  }

  // 查找单个记录
  async findOne(where) {
    const { ctx } = this;
    if (typeof where === 'object') {
      return await ctx.model.CourseRecord.findOne({ where });
    }
    return await ctx.model.CourseRecord.findByPk(where);
  }
}

module.exports = CourseRecordService;
